package com.kuang.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @项目名称：springcloud
 * @包名：com.kuang.myrule
 * @类名称：RandomRule
 * @类描述：
 * @创建人：liux @创建时间：2021年09月01日  10:52
 * @修改人：liux @修改时间：2021年09月01日  10:52
 * @修改备注
 * @版本信息：v1.0
 */
public class KuangRandomRule extends AbstractLoadBalancerRule {
    int total = 0;
    int crrentIndex = 0;
//    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                if(total < 5){
                    server = upList.get(crrentIndex);
                    total++;
                }else{
                    total = 0;
                    crrentIndex ++;
                    if (crrentIndex > upList.size()){
                        crrentIndex = 0;
                    }
                    server = upList.get(crrentIndex);
                }



//                int index = this.chooseRandomInt(serverCount);
//                server = (Server)upList.get(index);
                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
